<!--
 * @Author: ZAL 2177624751@qq.com
 * @Date: 2025-03-31 21:30:00
 * @LastEditors: ZAL 2177624751@qq.com
 * @LastEditTime: 2025-03-31 21:30:00
 * @Description: 退换/售后页面
-->
<template>
  <view class="container">
    <!-- 顶部标签页 -->
    <view class="tabs">
      <view 
        class="tab-item" 
        :class="{ active: activeTab === 'processing' }"
        @click="switchTab('processing')"
      >
        处理中
      </view>
      <view 
        class="tab-item" 
        :class="{ active: activeTab === 'completed' }"
        @click="switchTab('completed')"
      >
        已完成
      </view>
    </view>

    <!-- 售后列表 -->
    <scroll-view 
      class="aftersale-list" 
      scroll-y 
      @scrolltolower="loadMore"
      v-if="aftersaleList.length > 0"
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <view 
        class="aftersale-item" 
        v-for="item in aftersaleList" 
        :key="item.id"
      >
        <!-- 售后单头部 -->
        <view class="aftersale-header">
          <text class="aftersale-no">售后单号：{{ item.aftersaleNo }}</text>
          <text class="aftersale-status" :class="item.statusClass">{{ item.statusText }}</text>
        </view>

        <!-- 商品信息 -->
        <view class="product-info">
          <image :src="item.product.fruitImage" mode="aspectFill" class="product-image" />
          <view class="product-detail">
            <text class="product-name">{{ item.product.fruitName }}</text>
            <text class="product-spec" v-if="item.product.specifications">{{ item.product.specifications }}</text>
            <view class="product-price-wrap">
              <text class="product-price">￥{{ item.product.price }}</text>
              <text class="product-quantity">x{{ item.product.quantity }}</text>
            </view>
          </view>
        </view>

        <!-- 申请信息 -->
        <view class="apply-info">
          <view class="info-item">
            <text class="label">退款金额：</text>
            <text class="value price">￥{{ item.refundAmount }}</text>
          </view>
          <view class="info-item">
            <text class="label">申请原因：</text>
            <text class="value">{{ item.reason }}</text>
          </view>
          <view class="info-item">
            <text class="label">申请时间：</text>
            <text class="value">{{ formatDate(item.createTime) }}</text>
          </view>
        </view>

        <!-- 进度时间轴 -->
        <view class="progress-timeline">
          <view 
            class="timeline-item"
            v-for="(progress, index) in item.progress"
            :key="index"
            :class="{ active: progress.active }"
          >
            <view class="timeline-dot"></view>
            <view class="timeline-content">
              <text class="timeline-title">{{ progress.title }}</text>
              <text class="timeline-time">{{ progress.time }}</text>
            </view>
          </view>
        </view>

        <!-- 操作按钮 -->
        <view class="action-buttons" v-if="item.actions && item.actions.length > 0">
          <button 
            v-for="action in item.actions"
            :key="action.type"
            :class="action.type"
            @click="handleAction(action.type, item)"
          >
            {{ action.text }}
          </button>
        </view>
      </view>

      <!-- 无更多数据提示 -->
      <view class="no-more" v-if="!hasMore">
        没有更多售后记录了
      </view>
    </scroll-view>

    <!-- 空状态 -->
    <view v-else class="empty-state">
      <image src="/static/images/empty-aftersale.png" mode="aspectFit" class="empty-image" />
      <text>暂无售后记录</text>
      <button class="btn-apply" @click="navigateToApply">申请售后</button>
    </view>

    <!-- 加载提示 -->
    <u-loading-page :loading="loading"></u-loading-page>

    <!-- 取消申请确认弹窗 -->
    <u-popup v-model="showCancelDialog" mode="center">
      <view class="dialog-content">
        <view class="dialog-title">确认取消售后申请？</view>
        <view class="dialog-desc">取消后将无法恢复，请谨慎操作</view>
        <view class="dialog-buttons">
          <button class="btn-cancel" @click="showCancelDialog = false">再想想</button>
          <button class="btn-confirm" @click="confirmCancel">确认取消</button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onLoad, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app'
import { useOrderStore } from '../../store/orderStore.js'

// 创建store
const orderStore = useOrderStore()

// 数据状态
const activeTab = ref('processing')
const refreshing = ref(false)
const loading = ref(false)
const showCancelDialog = ref(false)
const currentItem = ref(null)

// 计算属性
const aftersaleList = computed(() => {
  // 对原始售后列表数据进行处理
  return orderStore.getAftersaleList.map(item => {
    // 根据售后状态添加UI所需的数据
    const statusMap = {
      0: { text: '等待商家处理', class: 'status-pending' },
      1: { text: '商家已同意', class: 'status-processing' },
      2: { text: '退款完成', class: 'status-success' },
      3: { text: '已拒绝', class: 'status-failed' },
      4: { text: '已取消', class: 'status-cancelled' }
    };
    
    const status = statusMap[item.status] || { text: '处理中', class: 'status-pending' };
    
    // 生成进度时间轴
    const progress = [
      {
        title: '售后申请已提交',
        time: formatDate(item.createTime),
        active: true
      },
      {
        title: '等待商家处理',
        time: item.status >= 1 ? formatDate(item.updateTime) : '',
        active: item.status >= 0
      },
      {
        title: item.status === 3 ? '商家拒绝申请' : '商家同意申请',
        time: item.status >= 1 ? formatDate(item.updateTime) : '',
        active: item.status >= 1
      },
      {
        title: '退款完成',
        time: item.status === 2 ? formatDate(item.updateTime) : '',
        active: item.status === 2
      }
    ];
    
    // 处理可用操作按钮
    const actions = [];
    if (item.status === 0) {
      actions.push({ type: 'cancel', text: '取消申请' });
    }
    
    actions.push({ type: 'contact', text: '联系客服' });
    
    return {
      ...item,
      statusText: status.text,
      statusClass: status.class,
      progress,
      actions
    };
  });
});

const pagination = computed(() => orderStore.getAftersalePagination);
const hasMore = computed(() => {
  return pagination.value.page * pagination.value.pageSize < pagination.value.total;
});

// 页面加载
onLoad((options) => {
  if (options.type) {
    activeTab.value = options.type;
  }
  loadAftersaleList();
});

// 下拉刷新
const onRefresh = async () => {
  refreshing.value = true;
  await loadAftersaleList(true);
  refreshing.value = false;
};

// 切换标签
const switchTab = (tab) => {
  activeTab.value = tab;
  loadAftersaleList(true);
};

// 获取售后列表
const loadAftersaleList = async (reset = false) => {
  try {
    loading.value = true;
    
    // 状态映射
    const statusMap = {
      'processing': 'processing', // 处理中
      'completed': 'completed'    // 已完成
    };
    
    const status = statusMap[activeTab.value];
    const page = reset ? 1 : pagination.value.page;
    
    await orderStore.loadAftersaleList({
      status,
      page,
      pageSize: 10
    });
  } catch (error) {
    console.error('获取售后列表失败', error);
    uni.showToast({
      title: '获取售后列表失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
    uni.stopPullDownRefresh();
  }
};

// 加载更多
const loadMore = () => {
  if (!hasMore.value || loading.value) return;
  
  const nextPage = pagination.value.page + 1;
  const statusMap = {
    'processing': 'processing',
    'completed': 'completed'
  };
  
  orderStore.loadAftersaleList({
    status: statusMap[activeTab.value],
    page: nextPage,
    pageSize: 10
  });
};

// 处理按钮操作
const handleAction = (type, item) => {
  switch (type) {
    case 'cancel':
      currentItem.value = item;
      showCancelDialog.value = true;
      break;
    case 'contact':
      uni.showToast({
        title: '联系客服功能开发中',
        icon: 'none'
      });
      break;
    default:
      break;
  }
};

// 确认取消申请
const confirmCancel = async () => {
  if (!currentItem.value) return;
  
  try {
    const res = await orderStore.cancelAftersale(currentItem.value.aftersaleNo);
    
    if (res && res.code === 200) {
      uni.showToast({
        title: '取消成功',
        icon: 'success'
      });
      showCancelDialog.value = false;
      
      // 刷新售后列表
      loadAftersaleList(true);
    } else {
      uni.showToast({
        title: res.message || '取消申请失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('取消申请失败', error);
    uni.showToast({
      title: '取消申请失败',
      icon: 'none'
    });
  }
};

// 跳转到申请页面
const navigateToApply = () => {
  uni.navigateTo({
    url: '/pages/order/apply-aftersale'
  });
};

// 日期格式化
const formatDate = (dateString) => {
  if (!dateString) return '';
  
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: env(safe-area-inset-bottom);
}

.tabs {
  display: flex;
  background-color: #ffffff;
  padding: 20rpx 0;
  position: sticky;
  top: 0;
  z-index: 100;

  .tab-item {
    flex: 1;
    text-align: center;
    font-size: 28rpx;
    color: #666666;
    position: relative;
    padding: 20rpx 0;

    &.active {
      color: #1890ff;
      font-weight: bold;

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 40rpx;
        height: 4rpx;
        background-color: #1890ff;
        border-radius: 2rpx;
      }
    }
  }
}

.aftersale-list {
  height: calc(100vh - 88rpx);
}

.aftersale-item {
  margin: 20rpx;
  background-color: #ffffff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

  .aftersale-header {
    padding: 20rpx;
    border-bottom: 1rpx solid #f0f0f0;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .aftersale-no {
      font-size: 24rpx;
      color: #999999;
    }

    .aftersale-status {
      font-size: 24rpx;
      font-weight: bold;

      &.status-pending {
        color: #1890ff;
      }

      &.status-processing {
        color: #40a9ff;
      }

      &.status-success {
        color: #52c41a;
      }

      &.status-failed {
        color: #ff4d4f;
      }
      
      &.status-cancelled {
        color: #999999;
      }
    }
  }

  .product-info {
    padding: 20rpx;
    display: flex;
    border-bottom: 1rpx solid #f0f0f0;

    .product-image {
      width: 160rpx;
      height: 160rpx;
      border-radius: 8rpx;
      margin-right: 20rpx;
    }

    .product-detail {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .product-name {
        font-size: 28rpx;
        color: #333333;
        margin-bottom: 10rpx;
      }

      .product-spec {
        font-size: 24rpx;
        color: #999999;
        margin-bottom: 10rpx;
      }

      .product-price-wrap {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .product-price {
          font-size: 28rpx;
          color: #1890ff;
          font-weight: bold;
        }

        .product-quantity {
          font-size: 24rpx;
          color: #999999;
        }
      }
    }
  }

  .apply-info {
    padding: 20rpx;
    border-bottom: 1rpx solid #f0f0f0;

    .info-item {
      display: flex;
      margin-bottom: 10rpx;

      &:last-child {
        margin-bottom: 0;
      }

      .label {
        font-size: 24rpx;
        color: #999999;
        width: 140rpx;
      }

      .value {
        flex: 1;
        font-size: 24rpx;
        color: #333333;

        &.price {
          color: #1890ff;
          font-weight: bold;
        }
      }
    }
  }

  .progress-timeline {
    padding: 30rpx 20rpx;
    border-bottom: 1rpx solid #f0f0f0;

    .timeline-item {
      display: flex;
      align-items: flex-start;
      position: relative;
      padding-bottom: 30rpx;

      &:last-child {
        padding-bottom: 0;
      }

      &::before {
        content: '';
        position: absolute;
        left: 6rpx;
        top: 24rpx;
        width: 2rpx;
        height: calc(100% - 24rpx);
        background-color: #e8e8e8;
      }

      &:last-child::before {
        display: none;
      }

      &.active {
        .timeline-dot {
          background-color: #1890ff;
        }

        .timeline-content {
          .timeline-title {
            color: #333333;
            font-weight: bold;
          }
        }
      }

      .timeline-dot {
        width: 14rpx;
        height: 14rpx;
        border-radius: 50%;
        background-color: #e8e8e8;
        margin-right: 20rpx;
        margin-top: 8rpx;
      }

      .timeline-content {
        flex: 1;

        .timeline-title {
          font-size: 26rpx;
          color: #999999;
          margin-bottom: 4rpx;
        }

        .timeline-time {
          font-size: 24rpx;
          color: #999999;
        }
      }
    }
  }

  .action-buttons {
    padding: 20rpx;
    display: flex;
    justify-content: flex-end;
    gap: 20rpx;

    button {
      font-size: 24rpx;
      padding: 10rpx 30rpx;
      border-radius: 30rpx;
      background-color: #ffffff;

      &.cancel {
        border: 1rpx solid #999999;
        color: #666666;
      }

      &.contact {
        border: 1rpx solid #1890ff;
        color: #1890ff;
      }
    }
  }
}

.no-more {
  text-align: center;
  padding: 30rpx;
  font-size: 24rpx;
  color: #999999;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding-top: 200rpx;

  .empty-image {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 20rpx;
  }

  text {
    font-size: 28rpx;
    color: #999999;
    margin-bottom: 40rpx;
  }

  .btn-apply {
    width: 240rpx;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
    color: #ffffff;
    border-radius: 40rpx;
    font-size: 28rpx;
  }
}

.dialog-content {
  width: 560rpx;
  background-color: #ffffff;
  border-radius: 12rpx;
  overflow: hidden;

  .dialog-title {
    font-size: 32rpx;
    color: #333333;
    font-weight: bold;
    text-align: center;
    padding: 40rpx 30rpx 20rpx;
  }

  .dialog-desc {
    font-size: 26rpx;
    color: #999999;
    text-align: center;
    padding: 0 30rpx 40rpx;
  }

  .dialog-buttons {
    display: flex;
    border-top: 1rpx solid #f0f0f0;

    button {
      flex: 1;
      height: 88rpx;
      line-height: 88rpx;
      text-align: center;
      font-size: 28rpx;
      background-color: #ffffff;

      &.btn-cancel {
        color: #666666;
        border-right: 1rpx solid #f0f0f0;
      }

      &.btn-confirm {
        color: #1890ff;
      }
    }
  }
}
</style> 